#! /usr/bin/env python

# simcraft2.py 
# branch
# v0.0.1


import os
from PyQt4 import QtGui,QtCore
import re
import Image
#import PIL
from PIL.ImageQt import ImageQt
import sys


class SC2Buttons(QtGui.QGraphicsPixmapItem):
    def __init__(self):
        super(SC2Buttons,self).__init__()
        
        self.setPixmap(QtGui.QPixmap('icons/misc/unit-targetingdrone.png'))
        
        # x,y of the button
        self.x
        self.y

        # config variables
        self.race = "None"
        self.type = "None"
        self.category = "None"
        self.name = "None"
        self.icon = "None"
        self.normal = "None"
        self.highlight = "None"
        self.gridkey = "None"
        self.defaultkey = "None"
        self.menupos = "None"
        self.action = "None"
        self.menu = "None"
        
        #class variables
        self.Pix_icon = ""
        self.Pix_normal = ""
        self.Pix_highlight = ""
        self.Pix_grayscale = ""

    def Init(self):

        # load icons
        self.Pix_icon = QtGui.QPixmap('icons/Protoss/%s' % ( self.icon ))
        self.Pix_normal = QtGui.QPixmap('icons/Protoss/%s' % ( self.normal ))
        self.Pix_highlight = QtGui.QPixmap('icons/Protoss/%s' % ( self.highlight ))
        self.Pix_grayscale = QtGui.QPixmap()
        # combine and create grayscale.
        
        qpainter = QtGui.QPainter(self.Pix_normal)
#        qpainter.setCompositionMode(19)
        qpainter.drawPixmap(0,0,self.Pix_icon)
        qpainter.end()

        self.setPixmap(self.Pix_normal)

        qpainter = QtGui.QPainter(self.Pix_highlight)
        qpainter.drawPixmap(0,0,self.Pix_icon)
        qpainter.end()
        
        

    def SetIcon(self,string):
        self.icon = string

    def SetNormal(self,string):
        self.normal = string

    def SetHighlight(self,string):
        self.highlight = string

    def SetRace(self,string):
        self.race = string

    def SetType(self,string):
        self.type = string

    def SetCategory(self,string):
        self.category = string

    def SetName(self,string):
        self.name = string

    def SetGridKey(self,string):
        self.gridkey = string

    def SetDefaultKey(self,string):
        self.defaultkey = string

    def SetMenuPos(self,string):
        self.menupos = string
        s = re.split(',',string)
        self.x = (int(s[0])-1)*76
        self.y = (int(s[1])-1)*76
        self.setPos(self.x,self.y)

    def SetAction(self,string):
        self.action = string

    def SetMenu(self,string):
        self.menu = string

    def DoAction(self):
        print self.action
        self.Push()
        

    def Push(self):
        self.setPixmap(self.Pix_highlight)

    def Release(self):
        self.setPixmap(self.Pix_normal)


class SC2Menus():
    def __init__(self):
        self.name = ""
        self.race = ""
        self.type = ""
        self.item = []


class SC2ButtonsView(QtGui.QGraphicsView):
    def __init__(self):
        super(SC2ButtonsView,self).__init__()
        
        self.setGeometry (300 , 300 , 380 , 228)
        self.setSceneRect (0 , 0 , 380 , 228)
        self.setBackgroundBrush ( QtGui . QColor (0 , 0 , 0))
        self.setRenderHint ( QtGui . QPainter . Antialiasing )
        policy = QtCore.Qt.ScrollBarAlwaysOff
        
        self.setVerticalScrollBarPolicy(policy)
        self.setHorizontalScrollBarPolicy(policy)

        self.init()
        
    def init(self):
                
        p_config="configs/protoss.properties"
        fh = open(p_config,'r')
        
        # holds all sc2 game buttons
        self.SC2Buttons = {}
        # holds all sc2 game menues 
        self.SC2Menus = {}
        # holds available key events for a menu
        self.keys = {}
        # holds available actions for a menu
        self.b_actions = {}

        # temporary hash for later processing for each entity of config
        entity = {}
        entityname = ""

        statusofconfig = "closed"
        for line in fh:
            #  print line
            line = line.rstrip("\n")
            if '#' in line:  # skip comment lines
                continue
            
            # new entity
            if '[' in line:
                print "Config Processing: Found beginning of a new Entity."
                if statusofconfig == "open":
                    print "Config Processing: ERROR Found new Entity without ending the previous one @: \"%s\"" % (line)
                else:
                    match = re.search('\[(.+)\]',line)
                    if match:
                        print "Config Processing: \__> Name of Entity: \"%s\"" % (match.group(1))
#                        self.entity[m.group(1)]=Sim_Entity()
                        entityname = match.group(1)
                        statusofconfig = "open"
                        
                    else:
                        print "Config Processing: \__> ERROR: Problem Matching [<name>]. Line is \"%s\"" % (line)
                        sys.exit(1)
                    continue
    
            if ';;' in line:
                print "Config Processing: \__> Found end of Entity section"
                if statusofconfig == "closed":
                    print "Config Processing: \__> ERROR: Found ';;' without a start []"
                    sys.exit(1)
                
                print "Config Processing: \__> Processing ..."
                
                if entity["type"]=="button":
                    print "Config Processing: \____> Creating Button Entity: \"%s\"" % ( entityname )
                    self.SC2Buttons[entity["name"]]=SC2Buttons()
                    self.SC2Buttons[entity["name"]].race=entity["race"]
                    self.SC2Buttons[entity["name"]].type=entity["type"]
                    self.SC2Buttons[entity["name"]].category=entity["category"]
                    self.SC2Buttons[entity["name"]].name=entity["name"]
                    self.SC2Buttons[entity["name"]].icon=entity["icon"]
                    self.SC2Buttons[entity["name"]].normal=entity["normal"]
                    self.SC2Buttons[entity["name"]].highlight=entity["highlight"]
                    self.SC2Buttons[entity["name"]].gridkey=entity["gridkey"]
                    self.SC2Buttons[entity["name"]].defaultkey=entity["defaultkey"]
                    self.SC2Buttons[entity["name"]].SetMenuPos(entity["menupos"])
                    self.SC2Buttons[entity["name"]].action=entity["action"]
                    self.SC2Buttons[entity["name"]].menu=entity["menu"]
                    print "Config Processing: \____> SC2Buttons.Init()"
                    self.SC2Buttons[entity["name"]].Init()
                    entity.clear()
                    statusofconfig = "closed"
                    continue

                if entity["type"]=="menu":
                    print "Config Processing: \____> Creating Menu Entity: \"%s\"" % ( entityname )
                    self.SC2Menus[entity["name"]]=SC2Menus()
                    self.SC2Menus[entity["name"]].race=entity["race"]
                    self.SC2Menus[entity["name"]].type=entity["type"]
                    self.SC2Menus[entity["name"]].name=entity["name"]
                    split = re.split(',',entity["items"])
                    for i in split:
                        print "splitted items from menu: %s"  % (i) 
                        self.SC2Menus[entity["name"]].item.append(i)
                    entity.clear()
                    continue                

            # add key,value to entity
            m = re.search('(\w+)=(.+)',line)
            
            if m:
                key=m.group(1)
                value=m.group(2)
                print "Config Processing: \____> Found Key: \"%s\" Value: \"%s\"" % (key,value)
                entity[key]=value


        fh.close()

        print "Config Processing: Done."

        self.scene = QtGui.QGraphicsScene()
        self.setScene(self.scene)
        # add main timer here


    def SetMenu(self,menu):
        # "Menu Probe"
        self.scene.clear()
        self.keys.clear()
        
        print "--> SetMenu Called with: \"%s\"" % (menu)
        for i in self.SC2Menus[menu].item:
            print "interate menu items: %s" % (i)
            self.scene.addItem(self.SC2Buttons[i])
            self.keys[self.SC2Buttons[i].gridkey]=self.SC2Buttons[i]
            self.b_actions[self.SC2Buttons[i].action]=self.SC2Buttons[i]

        print self.keys
            
    def keyPressEvent(self, e):

        key = e.key()

        print "Pressed: %s-%s-" % (key,e.nativeModifiers())
        for i in self.keys.iterkeys():
            if int(i) == int(key):
                self.keys[i].Push()
                self.doAction(self.keys[i].action)
    

    def keyReleaseEvent(self, e):

        key = e.key()
        print "Released: %s-%s-" % (key,e.nativeModifiers())
        for i in self.keys.iterkeys():
            if int(i) == int(key):
                self.keys[i].Release()

    def doAction(self,action):
        print action
        if action == "a_buildstructure":
            print self.b_actions[action].menu
            self.SetMenu(self.SC2Menus[self.b_actions[action].menu].name)


class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example,self).__init__()
        
        hbox = QtGui.QHBoxLayout()
        self.view = SC2ButtonsView()
        hbox.addWidget(self.view)
        self.setLayout(hbox)
        self.setWindowTitle("simcraft")
        self.view.SetMenu("Menu Probe")

app = QtGui.QApplication([])
ex = Example()
ex.show()
app.exec_()
